<template>
  <div class="home">
    <DialogOut
      :isGetOUt="isGetOUt"
      :gameId="getOutItem && getOutItem.id"
      betPoolInID="1"
      @isGetOutDia="isGetOutDia"
    ></DialogOut>
    <Bets
      :isBet="isBet"
      :gameId="gameId"
      :betId="betId"
      :betName="betName"
      @isBetData="closeBetData"
      :game="currentItem"
    ></Bets>
    <div class="time">
      <span>Response Countdown</span>
      <span>{{ time }}</span>
    </div>
    <div class="pool">
      <div class="teamWarp" v-for="(item, index) in schedules" :key="index">
        <div class="up">
          <h3>Pool Accumulation</h3>
          <div class="count">
            <img src="@/assets/img/logo.png" alt="" />
            <h2>{{ $formatNum(item.bet) }}</h2>
          </div>
        </div>
        <div class="team">
          <Status :status="item.status" :endTime="item.guessEnd"></Status>
          <div class="top">
            <div class="topItem">
              <span class="le">{{ item.homeTeam && item.homeTeam.name }}</span>
              <span class="score">{{
                item.homeTeam && item.homeTeam.score
              }}</span>
            </div>

            <div class="ce">
              <img
                :src="item.homeTeam && toHttps(item.homeTeam.logo)"
                alt=""
                class="teamPic"
              />
              <div class="ceCenter">
                <span class="startime"
                  >UTC {{ startTime(item.startTime) }}</span
                >
                <img src="@/assets/img/zq.png" alt="" class="change" />
                <!-- <span class="eurName">{{item.contestName ? item.contestName : " "}}</span> -->
              </div>
              <img
                :src="item.awayTeam && toHttps(item.awayTeam.logo)"
                alt=""
                class="teamPic"
              />
            </div>

            <div class="topItemAn">
              <span class="score">{{
                item.awayTeam && item.awayTeam.score
              }}</span>
              <span class="le">{{ item.awayTeam && item.awayTeam.name }}</span>
            </div>
          </div>
          <div class="buttons">
            <div class="buttonW">
              <el-button
                type="warning"
                round
                class="button"
                @click="isBetData(item, 1)"
                >WIN</el-button
              >
            </div>

            <div class="buttonW buttonWce">
              <el-button
                type="warning"
                round
                class="button"
                @click="isBetData(item, 3)"
                >DRAW</el-button
              >
            </div>

            <div class="buttonW">
              <el-button
                type="warning"
                round
                class="button"
                @click="isBetData(item, 2)"
                >WIN</el-button
              >
            </div>
          </div>
          <div class="dn">
            <!-- <img
              src="@/assets/img/teampic.png"
              alt=""
              @click="isBetData(item, 1)"
            /> -->
            <Step :game="item"></Step>
            <!-- <img
              src="@/assets/img/teampic.png"
              alt=""
              @click="isBetData(item, 2)"
            /> -->
          </div>
        </div>
        <Investment
          @isGetOutDia="isGetOutDia"
          :userChips="item.userChips"
          :userBet="item.userBet"
          :status="item.status"
          :game="item"
          :list="(item.betlist && item.betlist) || []"
          :id="item.id"
          :userNumber="item.userNumber || 0"
          @updata="getUserData"
          v-show="item.betlist && item.betlist.length > 0"
        ></Investment>
      </div>
    </div>
  </div>
</template>

<script>
import Status from "@/components/status.vue"; //投注的状态
import Step from "@/components/step.vue"; //奖池状况
import Investment from "@/components/getIn.vue"; //参与投注的
import DialogOut from "@/components/getOut.vue"; //撤出弹框
import Bets from "@/components/getBets.vue"; //投注
import BigNumber from "bignumber.js";
import moment from "moment";
import {
  web3handle,
  getBlance,
  gamePoolInfoMapping,
  queryPoolEarn,
  withdrawBetPool,
  web3,
  isbsc,
  userInfoMapping,
} from "@/web3/index";
import { mapState, mapActions } from "vuex";
import Web3 from "web3";
// eslint-disable-next-line no-unused-vars
let subscription = null;
export default {
  data () {
    return {
      isConnect: false,
      isGetOUt: false,
      isBet: false,
      gameId: null,
      getOutItem: null,
      time: "",
      schedules: [], //赛程列表
      currentItem: "",
      loadings: "",
      betName: "", //投注的赛队
      betId: "", // 1 主胜   2克胜  3平
    };
  },
  components: {
    Status,
    Step,
    Investment,
    DialogOut,
    Bets,
  },
  methods: {
    ...mapActions(["setBlance"]),
    isConnectWallet () {
      //链接钱包
      this.isConnect = !this.isConnect;
    },
    isGetOutDia (item) {
      //撤资
      console.log(item);
      this.getOutItem = item;
      this.isGetOUt = !this.isGetOUt;
      // this.getUserData();
    },
    //撤资合约
    async withdraw () {
      //betPoolN. 1 主胜 2 客胜 3 平
      const handel = await web3handle(withdrawBetPool);
      if (handel) {
        const _withdraw = await handel(id, betPoolN);
        if (_withdraw) {
          console.log("撤资成功");
        }
      }
    },

    closeBetData () {
      this.isBet = !this.isBet;
    },
    isBetData (item, betId) {
      let endTime = item.guessEnd;
      let nowTime = moment.utc().unix();
      if (this.currentAccount == "") {
        this.message("Please connect to the wallet", 2);
        return false;
      }
      if (item.status == 0) {
        this.message("The game has not started", 2);
        return false;
      }
      if (item.status == 2) {
        this.message("The game is over", 2);
        return false;
      }
      if (nowTime > endTime) {
        this.message("Bets have been suspended", 2);
        return false;
      }

      if (!isbsc()) {
        //请切换到bsc网络
        return false;
      }
      this.betId = betId;
      if (betId == 1) {
        //投主胜
        this.betName = item.homeTeam.name;
      }
      if (betId == 2) {
        //投客胜
        this.betName = item.awayTeam.name;
      }
      if (betId == 3) {
        //投平
        this.betName = "";
      }
      const _item = item;
      this.isBet = !this.isBet;
      this.gameId = _item.id;
      item.betId = betId;
      this.currentItem = item;
    },
    // getlist () {
    //   let parmas = { name: "", pageNum: 1, pageSize: 10 };
    //   this.getHttp(this.api.schedules, parmas).then((res) => { //赛程列表  0 1 2 未开始 进行 结束
    //     console.log(res);
    //     if (res.data.records.length) {
    //       this.schedules = res.data.records.map((item) => {
    //         const _item = JSON.parse(JSON.stringify(item))
    //         //平局池子
    //         _item.betDrewNum = 0
    //         //主胜池子
    //         _item.betWinANum = 0
    //         //客胜池子
    //         _item.betWinBNum = 0
    //         //总奖池
    //         _item.bet = 0
    //         // const userEarn = await queryPoolEarn(item.id)
    //         //用户收益chips
    //         _item.userChips = 0
    //         //用户挖矿收益
    //         _item.userBet = 0
    //         return _item
    //       })
    //     }
    //   });
    // },
    getlist () {
      let parmas = { name: "", pageNum: 1, pageSize: 10 };
      const that = this;
      this.getHttp(this.api.schedules, parmas).then((res) => {
        //赛程列表  0 1 2 未开始 进行 结束
        console.log(res);
        this.loadingOver();
        if (res.data.records.length) {
          this.schedules = res.data.records.map((item) => {
            const _item = JSON.parse(JSON.stringify(item));
            //平局池子
            _item.betDrewNum = 0;
            //主胜池子
            _item.betWinANum = 0;
            //客胜池子
            _item.betWinBNum = 0;
            //总奖池
            _item.bet = 0;
            // const userEarn = await queryPoolEarn(item.id)
            //用户收益chips
            _item.userChips = 0;
            //除去用户本金其他金额
            _item.exceptSelfNum = 0
            //用户挖矿收益
            _item.userBet = 0;
            _item.userNumber = 0;
            _item.betlist = [];
            return _item;
          });
        }

        console.log("22222222");
        that.getUserData();
        if (this.currentAccount) {
          getBlance(() => {
            console.log("区块更新");
          });
        }
        subscription = web3.eth
          .subscribe("newBlockHeaders", (error) => {
            console.log(error);
            if (!error) {
              console.log("1212121");
              that.loadingOver();
              that.getUserData();
              if (this.currentAccount) {
                getBlance(() => {
                  console.log("区块更新");
                });
              }
              return;
            } else {
              console.log(121212);
            }
            console.error(error);
          })
          .on("connected", function () {
            console.log(1);
            that.loadingOver();
          })
          .on("data", () => {
            console.log(2);
            that.loadingOver();
          })
          .on("error", () => {
            that.loadingOver();
          });
      }).catch(() => {
        that.loadingOver();
      });
    },

    getUserData () {
      this.schedules.forEach((item, index) => {
        (async (item, index) => {
          const _item = this.schedules[index];
          if (isbsc()) {
            const result = await gamePoolInfoMapping(item.id);
            //平局池子
            _item.betDrewNum = result && result.betDrewNum || 0;
            //主胜池子
            _item.betWinANum = result && result.betWinANum || 0;
            //客胜池子
            _item.betWinBNum = result && result.betWinBNum || 0;
            //总奖池
            _item.bet = new BigNumber(Web3.utils.fromWei(result.betDrewNum))
              .plus(new BigNumber(Web3.utils.fromWei(result.betWinANum)))
              .plus(new BigNumber(Web3.utils.fromWei(result.betWinBNum)))
              .plus(new BigNumber(Web3.utils.fromWei(result.recycleNum)))
              .toFixed(4)
              .toString();
            //除去用户本金其他金额
            _item.exceptSelfNum = new BigNumber(Web3.utils.fromWei(result.betDrewNum))
              .plus(new BigNumber(Web3.utils.fromWei(result.betWinANum)))
              .plus(new BigNumber(Web3.utils.fromWei(result.betWinBNum)))
              .toFixed(4)
              .toString();
          }


          if (this.currentAccount && isbsc()) {
            const userEarn = await queryPoolEarn(item.id);
            //用户收益chips
            _item.userChips = (userEarn[0] && Web3.utils.fromWei(userEarn[0])) || 0;
            //用户挖矿收益
            _item.userBet =
              (userEarn[1] && Web3.utils.fromWei(userEarn[1])) || 0;
            _item.userNumber =
              (userEarn[0] &&
                userEarn[1] &&
                new BigNumber(_item.userChips)
                  .plus(new BigNumber(_item.userBet))
                  .toString()) || 0;


            //用户投注挖矿收益
            const betlistResult = await userInfoMapping(item.id);
            console.log(betlistResult);
            _item.betlist = [];
            if (betlistResult) {
              if (betlistResult.betWinANum - 0 > 0) {
                _item.betlist.push({
                  betNumber: new BigNumber(
                    Web3.utils.fromWei(betlistResult.betWinANum)
                  )
                    .toFixed(4)
                    .toString(),
                  betName: item.homeTeam.name,
                  betPoolN: 1,
                });
              }
              if (betlistResult.betWinBNum - 0 > 0) {
                _item.betlist.push({
                  betNumber: new BigNumber(
                    Web3.utils.fromWei(betlistResult.betWinBNum)
                  )
                    .toFixed(4)
                    .toString(),
                  betName: item.awayTeam.name,
                  betPoolN: 2,
                });
              }
              if (betlistResult.betDrewNum - 0 > 0) {
                _item.betlist.push({
                  betNumber: new BigNumber(
                    Web3.utils.fromWei(betlistResult.betDrewNum)
                  )
                    .toFixed(4)
                    .toString(),
                  betName: "draw",
                  betPoolN: 3,
                });
              }
            }
          }
          this.$set(this.schedules, index, _item);
        })(item, index);
      });
    },
    ShowCountDown () {
      setInterval(() => {
        var myDate = new Date();
        var h = myDate.getHours();
        var m = myDate.getMinutes();
        var s = myDate.getSeconds();
        var thisTime = h * 60 * 60 + m * 60 + s;
        var oneTime = 1 * 60 * 60;
        var nineTime = 9 * 60 * 60;
        var seventeen = 17 * 60 * 60;
        var intDiff = 0;
        console.log(thisTime, oneTime, nineTime, seventeen);
        if (0 < thisTime && thisTime < oneTime) {
          intDiff = oneTime - thisTime;
        }
        if (oneTime < thisTime && thisTime < nineTime) {
          intDiff = nineTime - thisTime;
        }
        if (nineTime < thisTime && thisTime < seventeen) {
          intDiff = seventeen - thisTime;
        }
        if (seventeen < thisTime && thisTime < 24 * 60 * 60) {
          intDiff = 25 * 60 * 60 - thisTime;
        }
        var day = Math.floor(intDiff / (60 * 60 * 24));
        var hour = Math.floor(intDiff / (60 * 60)) - day * 24;
        var minute = Math.floor(intDiff / 60) - day * 24 * 60 - hour * 60;
        var second =
          Math.floor(intDiff) -
          day * 24 * 60 * 60 -
          hour * 60 * 60 -
          minute * 60;
        if (hour <= 9) hour = "0" + hour;
        if (minute <= 9) minute = "0" + minute;
        if (second <= 9) second = "0" + second;
        this.time = `${hour} : ${minute} : ${second}`;
      }, 1000);
    },
    startTime (time) {
      return moment.unix(time).utc().format("YYYY/MM/DD HH:mm:ss");
    },
    changeAllCount (count) {
      let counts = Web3.utils.fromWei(count);
      return counts;
    },
    toHttps (urls) {
      let url = urls
      if (url.indexOf('http') != -1) {
        let result = 'https://' + url.split('://')[1]
        return result
      }
    }
  },
  async mounted () {
    this.ShowCountDown();
    this.loading("Please wait...");
    // setTimeout(()=>{
    //   this.loadingOver()
    // },5000)
    this.getlist();
    // if (!isbsc()) {
    //   return false
    // }
    // let setval = setInterval(() => {
    //   this.getDate();
    //   if (this.second < 0) {
    //     clearInterval(setval);
    //   }
    // }, 1000);
  },
  destroyed () {
    subscription &&
      subscription.unsubscribe(function (error, success) {
        if (success) {
          console.log("Successfully unsubscribed!");
        }
      });
  },
  computed: {
    ...mapState({
      currentAccount: (state) => state.account,
      blance: (state) => state.blance,
    }),
  },
  watch: {
    currentAccount: function (newValue) {
      if (isbsc()) {
        console.log("1212121");
        if (newValue) {
          getBlance(() => {
            this.getUserData();
          });
        }
        const that = this;
        console.log("22222222");
        subscription = web3.eth
          .subscribe("newBlockHeaders", (error) => {
            console.log(error);
            if (!error) {
              console.log("1212121");
              that.loadingOver();
              that.getUserData();
              if (newValue) {
                getBlance(() => {
                  console.log("区块更新");
                });
              }
              return;
            } else {
              console.log(121212);
            }
            console.error(error);
          })
          .on("connected", function () {
            console.log(1);
            that.loadingOver();
          })
          .on("data", () => {
            console.log(2);
            that.loadingOver();
          })
          .on("error", () => {
            that.loadingOver();
          });
      }
    },
  },
};
</script>
<style scoped lang='scss'>
.home {
  min-height: 930px;
  width: 1200px;
  margin: 0 auto;
  margin-top: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .time {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-top: 85px;
    width: 353px;
    height: 100px;
    background: #ff8484;
    border-radius: 11px;
    color: #fff;
    span:nth-child(1) {
      font-size: 16px;
    }
    span:nth-child(2) {
      font-weight: 600;
      font-size: 44px;
    }
  }
  .pool {
    display: flex;
    flex-direction: column;
    width: 700px;
    margin-top: 35px;
    align-items: center;
    .up {
      display: flex;
      flex-direction: column;
      justify-content: center;
      background-color: #eadee5;
      width: 700px;
      height: 100px;
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
      margin: 0 auto;
      h3 {
        color: #350505;
        font-size: 14px;
      }
    }
    .count {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;

      h2 {
        color: #621147;
        font-size: 34px;
      }
      img {
        width: 40px;
        margin-right: 10px;
      }
    }
  }
  .teamWarp {
    display: flex;
    flex-direction: column;
    margin-bottom: 42px;
  }
  .team {
    width: 1200px;
    position: relative;
    background: linear-gradient(270deg, #ffcbcb 0%, #d5f2ff 100%);
    border-radius: 10px;
    border: 4px solid #b968dc;
    height: 300px;
    padding: 30px;
    box-sizing: border-box;
    .top {
      display: flex;
      justify-content: center;
      align-items: center;
      .topItem {
        width: 250px;
        display: flex;
        align-items: center;
        margin-right: 30px;
        justify-content: flex-end;
      }

      .topItemAn {
        width: 250px;
        display: flex;
        align-items: center;
        margin-left: 30px;
      }
      .score {
        color: #333333;
        font-weight: 600;
        font-size: 36px;
      }
      .score:nth-child(1) {
        margin-right: 15px;
        margin-left: 0;
      }
      .score:nth-child(2) {
        margin-left: 15px;
        margin-right: 0;
      }

      .le {
        color: #333333;
        font-size: 36px;
        font-weight: 600;
      }
      .ce {
        display: flex;
        justify-content: center;
        align-items: center;
        .teamPic {
          width: 60px;
          height: 60px;
        }

        .ceCenter {
          width: 200px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          margin: 0 10px;
          .startime {
            color: #808080;
            font-size: 16px;
            font-weight: 600;
          }
          img {
            width: 100%;
            margin: 5px 0;
          }
        }
      }
    }
    .buttons {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 25px 0;
      .buttonW {
        width: 230px;
        display: flex;
        justify-content: center;
        .button {
          width: 150px;
          height: 52px;
          border-radius: 52px;
          font-size: 24px;
          font-weight: 600;
          background: #ffa31e;
        }
      }
      .buttonWce {
        width: 330px;
      }
    }
    .dn {
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0 auto;
      img {
        width: 130px;
        cursor: pointer;
      }
    }
  }
}
</style>